package com.beiding.jsonanalyzer.analyze.func.openfunc;

import com.beiding.jsonanalyzer.analyze.func.OneFunc;
import com.beiding.jsonanalyzer.analyze.func.base.EasyFunc;
import com.beiding.jsonanalyzer.analyze.func.base.OneFuncAdaptor;

/**
 * 日期格式化
 *
 * @author 丁常磊
 * @date 2022/5/19 11:23
 */

public class Substring {


    public static OneFunc of(Object key, int from, int to) {

        // substring(,from,to)

        return FuncUtils.buildForEasyFunc(new OneFuncAdaptor<EasyFunc>() {
            @Override
            protected EasyFunc newInstance() {
                return new EasyFunc() {
                    @Override
                    protected Object execute(Object o) {
                        if (o instanceof String) {
                            if (to >= from) {
                                try {
                                    return ((String) o).substring(from, to);
                                } catch (Exception e) {
                                    throw new RuntimeException("字符串截取异常! 原字符串: " + o + " from: " + from + " to:" + to, e);
                                }
                            } else {
                                try {
                                    return ((String) o).substring(from);
                                } catch (Exception e) {
                                    throw new RuntimeException("字符串截取异常! 原字符串: " + o + " from: " + from, e);
                                }
                            }
                        }
                        return null;
                    }

                    @Override
                    public String toString() {
                        if (to > 0) {
                            return "substring(" + core + "," + from + "," + to + ")";
                        } else {
                            return "substring(" + core + "," + from + ")";
                        }
                    }
                };
            }
        }, key);
    }

    public static OneFunc of(Object key, int from) {
        return of(key, from, -1);
    }

}
